package com.eqdd.yiqidian.ui.gongneng.renshi.quanxian;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.View;

import com.eqdd.yiqidian.AuthorityActivityCustom;
import com.eqdd.yiqidian.R;
import com.eqdd.yiqidian.adapter.SectionDividerItemDecoration;
import com.eqdd.yiqidian.adapter.recycleadapter.ItemClickSupport;
import com.eqdd.yiqidian.adapter.slimadapter.SlimAdapterEx;
import com.eqdd.yiqidian.adapter.slimadapter.SlimInjector;
import com.eqdd.yiqidian.adapter.slimadapter.viewinjector.IViewInjector;
import com.eqdd.yiqidian.base.AppConstent;
import com.eqdd.yiqidian.base.BaseActivity;
import com.eqdd.yiqidian.base.Config;
import com.eqdd.yiqidian.bean.SecondBean;
import com.eqdd.yiqidian.bean.ThirdBean;
import com.eqdd.yiqidian.bean.rebuild.CarManagerBean;
import com.eqdd.yiqidian.bean.rebuild.CheckListCheckerResultBean;
import com.eqdd.yiqidian.bean.rebuild.EmploymentListResultBean;
import com.eqdd.yiqidian.http.DialogCallBack;
import com.eqdd.yiqidian.http.HttpConfig;
import com.eqdd.yiqidian.http.HttpResult;
import com.eqdd.yiqidian.http.JsonConverter;
import com.eqdd.yiqidian.ui.select.SelectSingleStaffActivity;
import com.eqdd.yiqidian.utils.ListUtil;
import com.eqdd.yiqidian.utils.ToastUtil;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.convert.StringConvert;
import com.lzy.okgo.model.Response;
import com.lzy.okrx2.adapter.FlowableBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.Flowable;
import io.reactivex.functions.BiFunction;

public class AuthorityActivity extends BaseActivity {
    private AuthorityActivityCustom dataBinding;
    private SlimAdapterEx slimAdapterEx;
    private Bundle bundle;
    private Object chosenBean;
    private EmploymentListResultBean bean;
    private Map<String, String> typeMap = new HashMap<>();

    @Override
    public void initBinding() {
        dataBinding = DataBindingUtil.setContentView(this, R.layout.activity_quanxian);
        initTopTitleBar(View.VISIBLE, "权限设置");
    }

    @Override
    public void initData() {
        typeMap.put("通知", "1");
        typeMap.put("公告", "2");
        typeMap.put("3", "车辆管理员");
        typeMap.put("4", "车辆维修员");
        dataBinding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
        dataBinding.recyclerView.addItemDecoration(new SectionDividerItemDecoration(this, 1, 2, 1).setHeadHeight(30));
        slimAdapterEx = SlimAdapterEx.create().register(R.layout.list_item_55, new SlimInjector<CheckListCheckerResultBean>() {
            @Override
            public void onInject(CheckListCheckerResultBean data, IViewInjector injector) {
                injector.text(R.id.tv_left, data.getType() + "审批人")
                        .text(R.id.tv_right, data.getUname())
                        .text(R.id.bt_right, "修改")
                        .clicked(R.id.bt_right, v -> {
                            chosenBean = data;
                            bundle = new Bundle();
                            bundle.putString("departId", user.getDepartId() + "");
                            bundle.putString("companyId", user.getCompanyId() + "");
                            startActivityForResult(SelectSingleStaffActivity.class, bundle, slimAdapterEx.getData().indexOf(data));
                        });
            }
        }).register(R.layout.list_item_55, new SlimInjector<ThirdBean>() {
            @Override
            public void onInject(ThirdBean data, IViewInjector injector) {
                injector.text(R.id.tv_left, data.getFirst())
                        .text(R.id.tv_right, data.getSecond())
                        .text(R.id.bt_right, TextUtils.isEmpty(data.getThird()) ? "修改" : "添加")
                        .clicked(R.id.bt_right, v -> {
                            chosenBean = data;
                            bundle = new Bundle();
                            bundle.putString("departId", user.getDepartId() + "");
                            bundle.putString("companyId", user.getCompanyId() + "");
                            startActivityForResult(SelectSingleStaffActivity.class, bundle, slimAdapterEx.getData().indexOf(data));
                        });
            }
        }).register(R.layout.list_item_55, new SlimInjector<String>() {
            @Override
            public void onInject(String data, IViewInjector injector) {
                injector.text(R.id.tv_left, "最高领导人")
                        .text(R.id.tv_right, data)
                        .text(R.id.bt_right, "设置")
                        .visibility(R.id.bt_right, data.equals("未设置") ? View.VISIBLE : View.INVISIBLE)
                        .clicked(R.id.bt_right, v -> {
                            chosenBean = data;
                            bundle = new Bundle();
                            bundle.putString("departId", user.getDepartId() + "");
                            bundle.putString("companyId", user.getCompanyId() + "");
                            startActivityForResult(SelectSingleStaffActivity.class, bundle, slimAdapterEx.getData().indexOf(data));
                        });
            }
        }).register(R.layout.list_item_55, new SlimInjector<Integer>() {
            @Override
            public void onInject(Integer data, IViewInjector injector) {
                injector.text(R.id.tv_left, "离职审批人设置")
                        .invisible(R.id.tv_right)
                        .invisible(R.id.bt_right);
            }
        }).attachTo(dataBinding.recyclerView).updateData(new ArrayList());
        ItemClickSupport.addTo(dataBinding.recyclerView)
                .setOnItemClickListener((recyclerView, position, v) -> {
                    if (position == 5) {
                        startActivity(DimissionLeaderListActivity.class);
                    }
                });

    }

    @Override
    public void setView() {
        showLoading();
        Flowable<HttpResult<List<CheckListCheckerResultBean>>> checkerFlow = OkGo.<HttpResult<List<CheckListCheckerResultBean>>>post(HttpConfig.BASE_URL + HttpConfig.CHECK_LIST_CHECKER)
                .params("userGuid", user.getGuid())
                .params("companyId", user.getCompanyId())
                .converter(new JsonConverter<HttpResult<List<CheckListCheckerResultBean>>>() {
                    @Override
                    public void test() {
                        super.test();
                    }
                })
                .adapt(new FlowableBody<HttpResult<List<CheckListCheckerResultBean>>>());
        Flowable<HttpResult<String>> adminFlow = OkGo.<HttpResult<String>>post(HttpConfig.BASE_URL + HttpConfig.TOP_ADMIN)
                .params("companyId", user.getCompanyId())
                .converter(new JsonConverter<HttpResult<String>>() {
                    @Override
                    public void test() {
                        super.test();
                    }
                })
                .adapt(new FlowableBody<HttpResult<String>>());
        Flowable.combineLatest(checkerFlow, adminFlow, (listHttpResult, listHttpResult2) -> {
            slimAdapterEx.getData().add(listHttpResult2.getItems());
            slimAdapterEx.getData().addAll(listHttpResult.getItems());
            slimAdapterEx.getData().add(new ThirdBean("车辆管理员", "未设定", "0"));
            slimAdapterEx.getData().add(new ThirdBean("车辆保养/维修员", "未设定", "0"));
            slimAdapterEx.getData().add(1);
            slimAdapterEx.notifyItemRangeInserted(0, 6);
            return 1;

        }).subscribe(integer -> {
        }, e -> {
            hideLoading();
        }, () -> {
            hideLoading();
        });
//        OkGo.<HttpResult<List<CheckListCheckerResultBean>>>post(HttpConfig.BASE_URL + HttpConfig.CHECK_LIST_CHECKER)
//                .params("userGuid", user.getGuid())
//                .params("companyId", user.getCompanyId())
//                .execute(new DialogCallBack<HttpResult<List<CheckListCheckerResultBean>>>(AuthorityActivity.this) {
//                    @Override
//                    public void onSuccess(Response<HttpResult<List<CheckListCheckerResultBean>>> response) {
//                        HttpResult<List<CheckListCheckerResultBean>> httpResult = response.body();
//                        ToastUtil.showShort(httpResult.getMsg());
//                        if (httpResult.getStatus() == 200) {
//                            slimAdapterEx.updateData(httpResult.getItems());
//                        }
//                    }
//                });
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Config.INTENT_CONTENT) {
            bean = (EmploymentListResultBean) data.getSerializableExtra("bean");
            switch (requestCode) {
                case 1:
                case 2:
                    updateChecher();
                    break;
                case 3:
                case 4:
                    updateCarManager(requestCode);
                    break;

            }
        }
    }

    private void updateCarManager(int request) {
        OkGo.<HttpResult>post(HttpConfig.BASE_URL + HttpConfig.SET_CAR_MANAGER)
                .params("userGuid", AppConstent.user.getGuid())
                .params("comid", AppConstent.user.getCompanyId())
                .params("adminGuid", bean.getGuid())
                .params("adminName", bean.getStaffName())
                .params("type", typeMap.get(request + ""))//type（0：车辆管理员，1：添加维护、保养的人）
                .execute(new DialogCallBack<HttpResult>(AuthorityActivity.this) {
                    @Override
                    public void onSuccess(Response<HttpResult> response) {
                        HttpResult httpResult = response.body();
                        ToastUtil.showShort(httpResult.getMsg());
                        if (httpResult.getStatus() == 200) {
                            ((ThirdBean) slimAdapterEx.getDataItem(request)).setSecond(bean.getStaffName());
                            slimAdapterEx.notifyItemChanged(request);
                        }
                    }
                });
    }

    private void updateChecher() {
        if (chosenBean instanceof String) {
            OkGo.<HttpResult>post(HttpConfig.BASE_URL + HttpConfig.SET_ADMIN)
                    .params("userGuid", AppConstent.user.getGuid())
                    .params("companyId", AppConstent.user.getCompanyId())
                    .params("topLeader", bean.getGuid())
                    .execute(new DialogCallBack<HttpResult>(AuthorityActivity.this) {
                        @Override
                        public void onSuccess(Response<HttpResult> response) {
                            HttpResult httpResult = response.body();
                            ToastUtil.showShort(httpResult.getMsg());
                            if (httpResult.getStatus() == 200) {
                                ((String) slimAdapterEx.getDataItem(0)).replace("未设置", bean.getStaffName());
                                slimAdapterEx.notifyItemChanged(0);
                            }
                        }
                    });
        } else {
            CheckListCheckerResultBean chosenBean = (CheckListCheckerResultBean) (this.chosenBean);
            OkGo.<HttpResult>post(HttpConfig.BASE_URL + HttpConfig.CHECK_SET_CHECKER)
                    .params("userGuid", user.getGuid())
                    .params("companyId", user.getCompanyId())
                    .params("approver", bean.getGuid())
                    .params("Id", chosenBean.getId())
                    .params("type", typeMap.get(chosenBean.getType()))
                    .execute(new DialogCallBack<HttpResult>(AuthorityActivity.this) {
                        @Override
                        public void onSuccess(Response<HttpResult> response) {
                            HttpResult httpResult = response.body();
                            ToastUtil.showShort(httpResult.getMsg());
                            if (httpResult.getStatus() == 200) {
                                chosenBean.setUname(bean.getStaffName());
                                slimAdapterEx.notifyItemChanged(slimAdapterEx.getData().indexOf(chosenBean));
                            }
                        }
                    });
        }
    }
}
